'''
Created on 10/04/2010

@author: User
'''

import gdata.youtube.service
from Models import DTO
import cgi

"""
import wsgiref.handlers
import urllib
import cgi
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext import db
from Models import DTO

import gdata.youtube
import gdata.youtube.service
import gdata.media
import gdata.geo
import gdata.alt.appengine
"""


class YoutubeUtils:
    def retrievePlaylistFeed(self):
        ytService = gdata.youtube.service.YouTubeService()
        playlist_feed = ytService.GetYouTubePlaylistFeed('http://gdata.youtube.com/feeds/api/users/ibizaah/playlists')
        dto = DTO()
        arr = []
        dto.playlistFeed = playlist_feed
        arr.append(dto)
        return 1
    
    def retrievePlaylistsNames(self):
        ytService = gdata.youtube.service.YouTubeService()
        playlist_feed = ytService.GetYouTubePlaylistFeed(username='default')
        dto = DTO()
        arr = []
        for entry in playlist_feed.entry:
            dto.playlistName = entry.title.text
            dto.id = entry.id.text.split('/')[-1]
            arr.append(dto)
        return arr
 
################################ authentication ##############################

    def GetAuthSubUrl(self):
        next = 'http://youtunes-tau2010.appspot.com/'
        scope = 'http://gdata.youtube.com'
        secure = False
        session = True
        yt_service = gdata.youtube.service.YouTubeService()
        return yt_service.GenerateAuthSubURL(next, scope, secure, session)
       
    def YoutubeLogin(self): 
        selfUrl = self.request.uri
        if (selfUrl.find('token') < 0):
            authSubUrl = self.GetAuthSubUrl()
            self.redirect(authSubUrl.to_string())           
        
        parameters = cgi.FieldStorage()
        authsub_token = parameters['token']        
        yt_service = gdata.youtube.service.YouTubeService()
        yt_service.SetAuthSubToken(authsub_token)
        yt_service.UpgradeToSessionToken()    
      
    """class AuthSub(webapp.RequestHandler): 
        def __init__(self): 
            self.current_user = None 
        self.token = 
        None 
        self.feed_url = 
        'http://gdata.youtube.com/feeds/api/users/default/uploads' 
        self.youtube_scope = 
        'http://gdata.youtube.com' 
        self.developer_key = 
        None 
        self.client = gdata.youtube.service.YouTubeService()
        gdata.alt.appengine.run_on_appengine(self.client)"""
      
    def feed_to_dto(self, feed):
        if feed is None: return None
        dto = DTO()
        #dto.name = song.name      
        return dto